<template>
  <BasicDrawer v-bind="$attrs" @register="registerDrawer" showFooter :title="getTitle" width="46%" @ok="handleSubmit">
    <BasicForm @register="registerForm">
    </BasicForm>
  </BasicDrawer>
</template>
<script lang="ts" setup>
import { ref, computed, unref } from 'vue';
import { BasicForm, useForm } from '@/components/Form';
import { formSchema } from './role.data';
import { BasicDrawer, useDrawerInner } from '@/components/Drawer';
import { sysAccountSave} from '@/api/demo/system';

const emit = defineEmits(['success', 'register']);
const isUpdate = ref(true);

const [registerForm, { resetFields, setFieldsValue, validate }] = useForm({
  labelWidth: 90,
  baseColProps: { span: 24 },
  schemas: formSchema,
  showActionButtonGroup: false,
});

const id = ref("")

const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
  resetFields();
  setDrawerProps({ confirmLoading: false });

  isUpdate.value = !!data?.isUpdate;
  id.value = "";
  if (unref(isUpdate)) {
    data.record.passWord=null;
    setFieldsValue({
      ...data.record,
    });
    id.value = data.record.sysUserId;
  }
});

const getTitle = computed(() => (!unref(isUpdate) ? '新增登录账号' : '编辑登录账号'));

async function handleSubmit() {
  try {
    const values = await validate();
    setDrawerProps({ confirmLoading: true });
    // TODO custom api

    values.sysUserId = id.value;
    sysAccountSave(values).then((res) => {
      if (res.code == 200) {
        closeDrawer();
        emit('success');
      }
    });

  } finally {
    setDrawerProps({ confirmLoading: false });
  }
}
</script>
